//
//  UIImage+ZJ.swift
//  ZJSwiftKit
//
//  Created by zyx on 2023/4/28.
//

import UIKit
// MARK: - Properties
extension ZJPrefix where Base: UIImage {
    
    /// 从图片中心点截取一个最大圆形区域图片
    public var circleImage: UIImage? {
        
        UIGraphicsBeginImageContextWithOptions(base.size, false, 0)
        defer {
            UIGraphicsEndImageContext()
        }
        
        guard let context = UIGraphicsGetCurrentContext() else { return nil }
        let imageWidth = base.size.width
        let imageHeight = base.size.height
        var rect: CGRect
        if imageWidth > imageHeight {
            let x = (imageWidth - imageHeight) * 0.5
            rect = CGRect.init(x: x, y: 0, width: imageHeight, height: imageHeight)
        } else if imageWidth == imageHeight {
            rect = CGRect.init(x: 0, y: 0, width: imageWidth, height: imageHeight)
        } else {
            let y = (imageHeight - imageWidth) * 0.5
            rect = CGRect.init(x: 0, y: y, width: imageWidth, height: imageWidth)
        }

        context.addEllipse(in: rect)
        context.clip()
        base.draw(in: rect)
        return UIGraphicsGetImageFromCurrentImageContext()
    }

}


// MARK: - Method
extension ZJPrefix where Base: UIImage {
    
    /// 压缩UIImage
    /// - Parameter quality: JPEG图像的质量，表示为0.0到1.0之间的值。值0.0表示最大压缩(或最低质量)，而值1.0表示最小压缩(或最佳质量)，(默认为0.5)。
    /// - Returns: 返回一张可选image
    public func compressed(quality: CGFloat = 0.5) -> UIImage? {
        
        guard let data = base.jpegData(compressionQuality: quality) else { return nil }
        
        return UIImage(data: data)
    }
    
    /// 更改图片颜色
    /// - Parameter color: 颜色
    /// - Returns: UIImage
    public func imageColor(_ color: UIColor?) -> UIImage {
        guard let color = color else { return base }
        UIGraphicsBeginImageContextWithOptions(base.size, false, base.scale)
        let context = UIGraphicsGetCurrentContext()
        context?.translateBy(x: 0, y: base.size.height)
        context?.scaleBy(x: 1.0, y: -1.0)
        context?.setBlendMode(.normal)
        let rect = CGRect(origin: .zero, size: base.size)
        context?.clip(to: rect, mask: base.cgImage!)
        color.setFill()
        context?.fill(rect)
        let newImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return newImage ?? base
    }

}
